package gwtool.backend;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

public class LocalStoreController {

	private DataSetController itemController;

	private CryptoController cryptoController = new CryptoController();

	private File localFile = new File(System.getProperty("user.home") + "/gwtool/cache.xml");

	public LocalStoreController(DataSetController itemController) {

		this.itemController = itemController;
	}

	public void clearCache() {

		localFile.delete();
	}

	public void loadCache() {

		Unmarshaller unmar;
		try {
			if (localFile.exists()) {
				unmar = JAXBContext.newInstance(LocalStoreItem.class).createUnmarshaller();
				Cipher c = cryptoController.getDecryptCipher(cryptoController.genAESPassFromUserPass(itemController
						.getBenutzter().getPassWord() + "KeyAES"));
				LocalStoreItem item = (LocalStoreItem) unmar.unmarshal(new StreamSource(new InputStreamReader(
						new CipherInputStream(new FileInputStream(localFile), c), "UTF-8")));
				if (item.getGruppen() != null) {
					itemController.getBenutzter().setGruppe(item.getGruppen());
				}
				if (item.getList() != null) {
					itemController.setDataSetsList(item.getList());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			localFile.delete();
		}
	}

	public void writeCache() {

		Marshaller marshaller;
		if (!localFile.getParentFile().exists()) {
			localFile.getParentFile().mkdirs();
		}
		if (!localFile.exists()) {
			try {
				localFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			marshaller = JAXBContext.newInstance(LocalStoreItem.class).createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			LocalStoreItem item = new LocalStoreItem(itemController.getDataSetList(), itemController.getBenutzter()
					.getGruppen());
			Cipher c = cryptoController.getEncryptCipher(cryptoController.genAESPassFromUserPass(itemController
					.getBenutzter().getPassWord() + "KeyAES"));
			OutputStreamWriter writer = new OutputStreamWriter(new CipherOutputStream(new FileOutputStream(localFile), c),
					"UTF-8");
			marshaller.marshal(item, writer);
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
